package com.example.mobifin_busticket.views.activities;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.Normalizer.Form;
import java.util.ArrayList;
import java.util.List;

import javax.security.auth.PrivateCredentialPermission;

import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;

import oauth.signpost.OAuthConsumer;
import oauth.signpost.basic.DefaultOAuthConsumer;

import com.example.mobifin_busticket.AppData;
import com.example.mobifin_busticket.BusTicketManagaer;
import com.example.mobifin_busticket.MyApplication;
import com.example.mobifin_busticket.R;
import com.example.mobifin_busticket.R.id;
import com.example.mobifin_busticket.R.layout;
import com.example.mobifin_busticket.R.menu;
import com.example.mobifin_busticket.Util;
import com.example.mobifin_busticket.controller.callbacks.ParseListner;
import com.example.mobifin_busticket.controller.callbacks.ResponseListener;
import com.example.mobifin_busticket.controller.databasemanager.DatabaseManager;
import com.example.mobifin_busticket.controller.networkmanager.NetworkManager;
import com.example.mobifin_busticket.models.BaseRequestEntityForBusTicketSeat;
import com.example.mobifin_busticket.models.BusModel;
import com.example.mobifin_busticket.models.PassengerDetails;
import com.example.mobifin_busticket.views.adapter.CustomListAdapterForTrips;
import com.example.mobifin_busticket.views.adapter.CustommenuListAdapter;
import com.example.mobifin_busticket.views.dialogs.CancelTicketDialog;
import com.example.mobifin_busticket.views.dialogs.PrintTicketDialog;

import android.support.v7.app.ActionBarActivity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class ContactDetailsActivity extends MobifinActivity implements
		OnClickListener {
	String source, destination, doj, fare, boardingpointId, tripId, sourceId,
			destinationId;
	ArrayList<String> SelectSeatlist = null;
	ArrayList<String> LadiesSeatList = null;
	ArrayList<Integer> fareList = null;
	TextView tvtriproute, tvTravellerName;
	RadioGroup rgGender;
	RadioButton rgslctGender;
	EditText etAge, etTravellerName, etEmail, etphNo;
	Button btn_requestPayment, btn_header_bck, btn_userSelectMenu;
	LinearLayout llMain, ll_Error, llChildError, ll_customMenu;
	List<EditText> allEds = new ArrayList<EditText>();
	List<EditText> allAge = new ArrayList<EditText>();
	ListView MenuList;
	CustommenuListAdapter listAdapter;

	int size, radId, noofField;
	boolean adultFlag;

	View contactView;
	String Gender, errorMessage;
	ArrayList<PassengerDetails> passengerList;
	PassengerDetails passengerModel;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_contact_details);
		tvtriproute = (TextView) findViewById(R.id.tvtripDetails);
		etEmail = (EditText) findViewById(R.id.edEnterEmail);
		etphNo = (EditText) findViewById(R.id.edphoneNo);
		llMain = (LinearLayout) findViewById(R.id.ll_travelDetails);
		ll_Error = (LinearLayout) findViewById(R.id.ll_error);
		llChildError = (LinearLayout) findViewById(R.id.ll_childErr);
		btn_requestPayment = (Button) findViewById(R.id.btn_payment);
		btn_header_bck = (Button) findViewById(R.id.header_back_btn);
		btn_header_bck.setOnClickListener(this);
		btn_requestPayment.setOnClickListener(this);
		ll_Error.setOnClickListener(this);
		btn_userSelectMenu = (Button) findViewById(R.id.btn_userSelectMenuinContact);
		MenuList = (ListView) findViewById(R.id.cnclList);
		ll_customMenu = (LinearLayout) findViewById(R.id.ll_customMenu);
		ll_customMenu.setOnClickListener(this);
		btn_userSelectMenu.setOnClickListener(this);

		SelectSeatlist = new ArrayList<String>();
		LadiesSeatList = new ArrayList<String>();
		fareList = new ArrayList<Integer>();
		fareList = AppData.fareList;
		boardingpointId = AppData.BoardingPointId;
		source = AppData.Source;
		destination = AppData.Destination;
		tripId = AppData.BusId;
		sourceId = AppData.SourceId;
		destinationId = AppData.DestinationId;
		doj = AppData.DateOfJourny;
		LadiesSeatList = getIntent().getStringArrayListExtra("LadiesSeatList");
		System.out.println("doj:" + doj);
		System.out.println("new list in contact:" + LadiesSeatList);
		fare = getIntent().getStringExtra("totalFare");
		SelectSeatlist = AppData.SeatLayout;
		btn_requestPayment.setText(getResources().getString(
				R.string.btn_requestPayment)
				+ " (" + fare + ")");
		tvtriproute.setText(source + " to " + destination + "   " + doj);
		init();

		ArrayList<String> listValue = new ArrayList<String>();
		listValue.add(getResources().getString(R.string.cancel_ticket));
		listValue.add(getResources().getString(R.string.print_ticket));
		listAdapter = new CustommenuListAdapter(ContactDetailsActivity.this,
				R.layout.custom_menu_list, listValue);
		MenuList.setAdapter(listAdapter);
		MenuList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				onMenuItemClick(position);
			}
		});

	}

	private void init() {
		// TODO Auto-generated method stub
		if (contactView == null) {
			for (int i = 0; i < SelectSeatlist.size(); i++) {
				LayoutInflater inflater = LayoutInflater
						.from(ContactDetailsActivity.this);
				contactView = inflater.inflate(R.layout.row_contact_details,
						null);
				tvTravellerName = (TextView) contactView
						.findViewById(R.id.tvTravellerName);
				etTravellerName = (EditText) contactView
						.findViewById(R.id.edTravellerName);
				allEds.add(etTravellerName);
				etAge = (EditText) contactView.findViewById(R.id.etage);
				allAge.add(etAge);
				rgGender = (RadioGroup) contactView
						.findViewById(R.id.radioGender);

				tvTravellerName.setText("Traveller name on seat "
						+ SelectSeatlist.get(i));
				llMain.addView(contactView);
				rgGender.setTag(SelectSeatlist.get(i));

			}
		}
	}

	protected void onMenuItemClick(int position) {
		// TODO Auto-generated method stub
		if (position == 0) {
			System.out.println("on click Cancle");
			CancelTicketDialog dialog = new CancelTicketDialog(
					ContactDetailsActivity.this);
			dialog.show();
			Util.mListHide(MenuList);
		}
		if (position == 1) {
			System.out.println("on click print");
			PrintTicketDialog pdialog = new PrintTicketDialog(
					ContactDetailsActivity.this);
			pdialog.show();
			Util.mListHide(MenuList);
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btn_payment:
			Util.mListHide(MenuList);
			onClickRequestPayment();
			break;
		case R.id.header_back_btn:
			Util.mListHide(MenuList);
			finish();
			break;
		case R.id.ll_error:
			Util.mListHide(MenuList);
			ll_Error.setVisibility(View.GONE);
			break;
		case R.id.btn_userSelectMenuinContact:
			Util.onClickUserMenu(ContactDetailsActivity.this, MenuList);
			break;
		case R.id.ll_customMenu:
			Util.onClickUserMenu(ContactDetailsActivity.this, MenuList);
			break;
		default:
			break;
		}

	}

	private void onClickRequestPayment() {
		// TODO Auto-generated method stub
		noofField = 1;
		errorMessage = "";
		adultFlag = false;
		Animation slide = AnimationUtils.loadAnimation(getApplicationContext(),
				R.anim.slidedown);
		String initailmsg = getResources().getString(
				R.string.bus_seerchbus_forget_title);
		conditionMbEm();
		for (int j = 0; j < SelectSeatlist.size(); j++) {
			insideForloop(j);
		}
		if (noofField == 1 && !adultFlag) {
			noofField++;
			errorMessage += ":"
					+ getResources().getString(R.string.ageadultalmsg);
		}
		errorMessage = initailmsg + errorMessage;
		if (noofField > 1) {
			ll_Error.startAnimation(slide);
			ll_Error.setVisibility(View.VISIBLE);
			Util.errorFieldcreationSeatselect(ContactDetailsActivity.this,
					llChildError, noofField, errorMessage);
		} else {
			setModelValue();
		}

	}

	private void insideForloop(int j) {
		// TODO Auto-generated method stub
		if (etAge.getText().toString().trim().length() > 0
				&& Integer.parseInt(etAge.getText().toString().trim()) > 12) {
			adultFlag = true;
		}
		if (j == 0) {
			if (etTravellerName.getText().toString().trim().length() == 0) {
				noofField++;
				errorMessage += ":"
						+ getResources().getString(R.string.namevalmsg) + " "
						+ SelectSeatlist.get(j);

			} else if (etAge.getText().toString().trim().length() == 0) {
				noofField++;
				errorMessage += ":"
						+ getResources().getString(R.string.agealmsg) + " "
						+ SelectSeatlist.get(j);
			} else if (rgGender.getCheckedRadioButtonId() == -1) {
				noofField++;
				errorMessage += ":"
						+ getResources().getString(R.string.radiomsg) + " "
						+ SelectSeatlist.get(j);
			}
		} else {
			insideelsevalidation(j);
		}

	}

	private void insideelsevalidation(int j) {
		// TODO Auto-generated method stub
		if (etTravellerName.getText().toString().trim().length() > 0
				&& etAge.getText().toString().trim().length() == 0
				&& rgGender.getCheckedRadioButtonId() == -1) {
			noofField += 2;
			errorMessage += ":" + getResources().getString(R.string.agealmsg)
					+ " " + SelectSeatlist.get(j) + ":"
					+ getResources().getString(R.string.radiomsg) + " "
					+ SelectSeatlist.get(j);
		} else if (etTravellerName.getText().toString().trim().length() == 0
				&& etAge.getText().toString().trim().length() > 0
				&& rgGender.getCheckedRadioButtonId() == -1) {
			noofField += 2;
			errorMessage += ":" + getResources().getString(R.string.namevalmsg)
					+ " " + SelectSeatlist.get(j) + ":"
					+ getResources().getString(R.string.radiomsg) + " "
					+ SelectSeatlist.get(j);
		} else if (etTravellerName.getText().toString().trim().length() == 0
				&& etAge.getText().toString().trim().length() == 0
				&& rgGender.getCheckedRadioButtonId() != -1) {
			noofField += 2;
			errorMessage += ":" + getResources().getString(R.string.namevalmsg)
					+ " " + SelectSeatlist.get(j) + ":"
					+ getResources().getString(R.string.agealmsg) + " "
					+ SelectSeatlist.get(j);
		} else {
			otherElsessubpart(j);
		}
	}

	private void otherElsessubpart(int j) {
		// TODO Auto-generated method stub
		if (etTravellerName.getText().toString().trim().length() == 0
				&& etAge.getText().toString().trim().length() > 0
				&& rgGender.getCheckedRadioButtonId() != -1) {
			noofField++;
			errorMessage += ":" + getResources().getString(R.string.namevalmsg)
					+ " " + SelectSeatlist.get(j);
		} else if (etTravellerName.getText().toString().trim().length() > 0
				&& etAge.getText().toString().trim().length() == 0
				&& rgGender.getCheckedRadioButtonId() != -1) {
			noofField++;
			errorMessage += ":" + getResources().getString(R.string.agealmsg)
					+ " " + SelectSeatlist.get(j);
		} else if (etTravellerName.getText().toString().trim().length() > 0
				&& etAge.getText().toString().trim().length() > 0
				&& rgGender.getCheckedRadioButtonId() == -1) {
			noofField++;
			errorMessage += ":" + getResources().getString(R.string.radiomsg)
					+ " " + SelectSeatlist.get(j);
		}
	}

	private void conditionMbEm() {
		String MobilePattern = "[0-9]{10}";
		if (etphNo.getText().toString().matches(MobilePattern)
				&& (etEmail.getText().toString().trim().length() > 0 && !Util
						.emailValidation(etEmail.getText().toString().trim()))) {
			noofField = 3;
			errorMessage = ":" + getResources().getString(R.string.mobileno)
					+ ":" + getResources().getString(R.string.emailvalidmasg);
		} else if (!etphNo.getText().toString().matches(MobilePattern)) {
			noofField = 2;
			errorMessage = ":" + getResources().getString(R.string.mobileno);
			etphNo.requestFocus();
		} else if (etEmail.getText().toString().trim().length() > 0
				&& !Util.emailValidation(etEmail.getText().toString().trim())) {
			noofField = 2;
			errorMessage = ":"
					+ getResources().getString(R.string.emailvalidmasg);
			etEmail.requestFocus();
		}
	}

	private void setModelValue() {
		// TODO Auto-generated method stub
		passengerList = new ArrayList<PassengerDetails>();

		for (int i = 0; i < SelectSeatlist.size(); i++) {
			passengerModel = new PassengerDetails();

			passengerModel.setseatName(SelectSeatlist);
			passengerModel.setfare(fareList);
			passengerModel.setladiesSeat(LadiesSeatList);

			rgGender = (RadioGroup) llMain.findViewWithTag(SelectSeatlist
					.get(i));
			radId = rgGender.getCheckedRadioButtonId();
			rgslctGender = (RadioButton) findViewById(radId);
			isLadiesSeat(i);
			if (i == 0) {
				passengerModel.setEmailId(etEmail.getText().toString());
				passengerModel.setphno(etphNo.getText().toString());
			}
			passengerModel.settravellerName(allEds.get(i).getText().toString());
			passengerModel.setage(allAge.get(i).getText().toString());
			passengerModel.setgender(rgslctGender.getText().toString());
			
			passengerList.add(passengerModel);
			passengerModel.setpassengerList(passengerList);

		}
		passengerModel.setavailableTripId(tripId);
		passengerModel.setboardingPointId(boardingpointId);
		passengerModel.setsource(sourceId);
		passengerModel.setdestination(destinationId);

		AppData.PassengerModel = passengerModel;
		Intent confromIntent = new Intent(ContactDetailsActivity.this,
				PinConformActivity.class);
		confromIntent.putIntegerArrayListExtra("fare", fareList);
		confromIntent.putExtra("source", source);
		confromIntent.putExtra("destination", destination);
		confromIntent.putExtra("doj", doj);
		confromIntent.putExtra("TotalSeat",
				String.valueOf(SelectSeatlist.size()));
		startActivityForResult(confromIntent, 1);

	}

	private void isLadiesSeat(int i) {
		// TODO Auto-generated method stub
		for (int j = 0; j < LadiesSeatList.size(); j++) {
			if (LadiesSeatList.get(j).equals("true")
					|| rgslctGender.getText().toString().equals("Female")) {
				passengerModel.setgender("Female");
				passengerModel.setTitle("Ms");
			} else {
				passengerModel.setgender("Male");
				passengerModel.setTitle("MR");
			}
		}
	}

}
